using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Asp.Versioning;

namespace MinimalApi;

public class ApiVersionFilter : IOperationFilter
{
    public void Apply(OpenApiOperation op, OperationFilterContext txt)
    {
        op.Parameters ??= new List<OpenApiParameter>();
        
        var isVersionMeta = txt.ApiDescription.ActionDescriptor.EndpointMetadata
            .Any(metadataItem => metadataItem is ApiVersionMetadata);
        if (isVersionMeta)
        {
            op.Parameters.Add(new OpenApiParameter
            {
                Name = "API-Version",
                In = ParameterLocation.Header,
                Description = "API Version header value",
                Schema = new OpenApiSchema
                {
                    Type = "String",
                    Default = new OpenApiString("1.0")
                }
            });
        }
    }
}